package com.sqlloader.views.widgets;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;

import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;

import com.sqlloader.provider.DataTableContentProvider;
import com.sqlloader.provider.DataTableLabelProvider;


public class DataTableViewer extends TableViewer {

	private int fieldnum=0;
	public int getFieldnum() {
		return fieldnum;
	}
	public void setFieldnum(int fieldnum) {
		this.fieldnum = fieldnum;
	}
	public DataTableViewer(Composite parent, int style) {
		super(parent, style);
		this.setContentProvider(new DataTableContentProvider());
		this.setLabelProvider(new DataTableLabelProvider());
	}
	public void loadFile(String filename)
	{
		this.fieldnum=0;
		Table table=this.getTable();
		table.removeAll();
		table.clearAll();
		TableColumn[] columns= table.getColumns();
		if(columns!=null&&columns.length>0)
		{
			for(int i=0,s=columns.length;i<s;i++)
			{
				columns[i].dispose();
			}
		}
		
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		Vector list=new Vector();
		try {
			File file=new File(filename);
			if(file.exists()){
			FileReader fr = new FileReader(filename);
			BufferedReader br = new BufferedReader(fr);
			String line="";
			
			line=br.readLine();
			if(line!=null)
			{
				String[] tokens=line.split(",");
				this.fieldnum=tokens.length;
				for(int i=0;i<this.fieldnum;i++)
				{
					TableColumn column=new TableColumn(table,SWT.NONE);
					column.setText("Field"+i);
					column.pack();
				}
				list.addElement(tokens);
			}
			while((line=br.readLine())!=null){
				list.addElement(line.split(","));
			}
			fr.close();
			br.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.setInput(list);
	}

}
